package cn.ren.cloud.mq.consumer;

import cn.ren.cloud.domain.PayOrder;
import cn.ren.cloud.dto.CourseOrderPayDto;
import cn.ren.cloud.enums.GlobelExceptionEnum;
import cn.ren.cloud.exception.GlobalCustomException;
import cn.ren.cloud.service.IPayOrderService;
import cn.ren.cloud.utils.AssertUtil;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.Date;

/**
 * @author 23508
 */
@Slf4j
@Component
@RocketMQMessageListener(consumerGroup = "course-pay-group", topic = "order-pay-topic", selectorExpression = "order-pay-tag")
public class CoursePayConsumer implements RocketMQListener<MessageExt> {

    private final IPayOrderService payOrderService;

    public CoursePayConsumer(IPayOrderService payOrderService) {
        this.payOrderService = payOrderService;
    }

    /**
     * 订单消息消费者
     *
     * @param messageExt
     */
    @Override
    public void onMessage(MessageExt messageExt) {
        byte[] body = messageExt.getBody();
        if (body.length == 0) {
            // 1.应该记录进入异常的次数，如果超过三次，那么应该通知管理员，手动处理
            log.error("支付消费发生异常，异常信息为：消息信息为空！");
            throw new GlobalCustomException(GlobelExceptionEnum.GLOBE_EXCEPTION_ENUM_PARAM_ERROR);
        }
        CourseOrderPayDto courseOrderPayDto = JSON.parseObject(new String(body, StandardCharsets.UTF_8), CourseOrderPayDto.class);
        String orderNo = courseOrderPayDto.getOrderNo();
        // 查询订单号
        PayOrder payOrder = payOrderService.selectByOrderNo(orderNo);
        if (payOrder != null) {
            log.info("支付服务消费订单时，订单已存在，订单号为：" + orderNo);
            return;
        }
        // 添加支付订单表
        payOrder = new PayOrder();
        payOrder.setPayType(courseOrderPayDto.getPayType());
        payOrder.setOrderNo(orderNo);
        payOrder.setUserId(courseOrderPayDto.getUserId());
        payOrder.setPayStatus(PayOrder.WAIT_PAY);
        payOrder.setAmount(courseOrderPayDto.getTotalAmount());
        payOrder.setCreateTime(new Date());
        payOrder.setSubject(courseOrderPayDto.getTitle());
        payOrder.setExtParams(JSON.toJSONString(courseOrderPayDto.getCourseOrderExtParamsDto()));
        payOrderService.insert(payOrder);
    }
}
